﻿using System.Collections.Specialized;
using System.Linq;
using SolutionUsingThreadsInModel.Common;
using SolutionUsingThreadsInModel.Common.Commands;
using SolutionUsingThreadsInModel.Model;

namespace SolutionUsingThreadsInModel.ViewModel
{
    public class ThousandsOfElementsInUIViewModel : ViewModelBase
    {
        private readonly ThousandsOfElementsInUIModel _model;
        public ObservableCollectionEx<SmallItemViewModel> SmallItems { get; set; }

        public ThousandsOfElementsInUIViewModel(ThousandsOfElementsInUIModel model)
        {
            _model = model;
            SmallItems = new ObservableCollectionEx<SmallItemViewModel>();
            
            _model.SmallItems.CollectionChanged += SmallItems_CollectionChanged;
        }

        
        void SmallItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if(e.Action == NotifyCollectionChangedAction.Add)
            {
                var newItem = (SmallItemModel)e.NewItems[0];
                SmallItems.Add(new SmallItemViewModel(newItem));
            }
            else if(e.Action == NotifyCollectionChangedAction.Remove)
            {
                var oldItem = (SmallItemModel)e.OldItems[0];
                var smallItemViewModel = SmallItems.FirstOrDefault(s => s.Id == oldItem.Id);
                if (smallItemViewModel != null)
                    SmallItems.Remove(smallItemViewModel);
            }
        }

        private RelayCommand _loadAllSmallItemsCommand;
        public RelayCommand LoadAllSmallItemsCommand
        {
            get { return _loadAllSmallItemsCommand ?? (_loadAllSmallItemsCommand = new RelayCommand(param => _model.CreateSmallItems())); }
        }


    }
}
